Skip to content

fix: support pickle protocols 0 and 1 with py::pickle - #6301

Open
henryiii wants to merge 7 commits into
pybind:masterfrom
henryiii:fix/pickle-protocol-0
Open

henryiii wants to merge 7 commits into
pybind:masterfrom
henryiii:fix/pickle-protocol-0

Conversation

@henryiii

@henryiii henryiii commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

This is one of the major pain points of pybind11, would be exciting if we can finally improve it.

Some Codex and Claude investigation showed three possible points:

This can cause a change in this case: class A(Bound, Mixin), where Mixin defines __reduce_ex__. The new one gets used instead of that. I think that's fine (easy to workaround, like putting the mixin first, etc.) All other combinations, like normal parents, etc. work fine if a user was overloading this.

Current promise of a type error is a bit too broad. Edit: fixed.

And finally, this can cause an extra lookup, about 5% on a trial class. If we pass the all_type_info result from pybind11_object_new into allocate_layout, then the lookup happens once. Edit: This is a trivial change, so I can push it to keep this minimal impact.

🤖 AI text below 🤖

Description

Fixes #3745.

With pickle protocols 0 and 1, copyreg._reduce_ex calls pybind11_object(self) on Python 3.9+. pybind11_object_new then threw a C++ exception through C frames, and the process aborted.

  • py::pickle() now also defines __reduce_ex__. It reduces as protocol 2 when the requested protocol is lower. The result is valid for all protocols, so these classes now round-trip on protocols 0 and 1.
  • pybind11_object_new raises TypeError when the type has no pybind11-registered base. Classes that bind __getstate__ and __setstate__ directly still do not support protocols 0 and 1. On CPython, dumps now raises this TypeError and no longer aborts.
  • The docs note that warned about memory corruption on protocols 0 and 1 now states the new behaviour.

The TypeError is not guaranteed. pybind11_object is shared across modules, so it applies only when the module that creates the base type has this fix. PyPy does not raise in dumps. The py::pickle() change is per class.

Suggested changelog entry:

  • Classes that use py::pickle() now support pickle protocols 0 and 1. Classes that bind __getstate__ and __setstate__ directly still do not support these protocols; on CPython, pickle.dumps now raises TypeError in most cases and no longer aborts the process.

Protocols 0 and 1 made copyreg call pybind11_object(self), which threw a
C++ exception through C frames and aborted the process on Python 3.9+.

py::pickle() now defines __reduce_ex__ to reduce as protocol 2 for lower
protocols. pybind11_object_new raises TypeError and no longer throws.

Fixes pybind#3745

Assisted-by: ClaudeCode:claude-fable-5-2
PyPy pickles a class without py::pickle() at protocols 0 and 1, then
segfaults on loads because __setstate__ runs on an uninitialized instance.

Assisted-by: ClaudeCode:claude-opus-5-5
@henryiii
henryiii marked this pull request as ready for review November 23, 2026 22:35
pybind11_object_new checked all_type_info(), then allocate_layout() looked
it up again. Pass the result through instead.

Assisted-by: ClaudeCode:claude-fable-5-2
The error depends on which module creates pybind11_object, and PyPy does
not raise it.

Assisted-by: ClaudeCode:claude-fable-5-2
…0 and 1

The automatic __reduce_ex__ now calls the next __reduce_ex__ in the MRO,
and a __reduce_ex__ bound on the same class replaces it. py::enum_ uses
the same helper.

Assisted-by: ClaudeCode:claude-fable-5-2
@henryiii
henryiii force-pushed the fix/pickle-protocol-0 branch from a6353e6 to 2118674 Compare November 24, 2026 17:20
@rwgk

rwgk commented Nov 28, 2026

Copy link
Copy Markdown
Collaborator

— codex on behalf of Ralf —

Preserve descriptor binding when delegating to an inherited __reduce_ex__. With class Derived(PickleBound, Mixin), both a mixin @classmethod and a mixin @staticmethod implementation round-trip on the base. On this head, the lookup on the class followed by an explicit self passes an extra argument. I reproduced the resulting TypeError with protocols 0, 1, 2, and 5 on CPython 3.9.25 and 3.15.2. After deciding whether to promote object's fallback, invoking the inherited method through super(cl, self) preserved descriptor binding on both versions in a scratch build. The existing 53 pickling tests passed on regular and free-threaded 3.15.2. Please add an inherited descriptor case to the regression coverage. MRO delegation

Generated by Codex. Ralf has yet to review these findings.

Use super() so an inherited classmethod or staticmethod __reduce_ex__
gets the right arguments.

Assisted-by: ClaudeCode:claude-opus-5-5
@henryiii

Copy link
Copy Markdown
Collaborator Author

🤖 AI text below 🤖

Fixed in 417a45c. The delegation now calls super(cl, self).__reduce_ex__(protocol), so inherited classmethod and staticmethod implementations get the correct binding. The MRO scan stays to decide if protocols 0 and 1 change to 2 for object's fallback. test_pickle_keeps_mixin_reduce_ex now has classmethod and staticmethod mixin cases. These cases failed with all protocols before the fix.

PyPy's Windows import library does not export PySuper_Type. Get super
from builtins at runtime.

Assisted-by: ClaudeCode:claude-opus-5-5

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]: Failed to pickle objects using protocol 0 from Python 3.9

2 participants